<?php
declare (strict_types=1);

namespace app\mall\logic\product;

use app\mall\model\product\ProductSearch as SearchMod;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 搜索接口
 */
class Search extends SearchMod
{

    /**
     * 添加搜索记录
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/18
     *
     * @param $search
     */
    public function addSearch($search)
    {
        $exist = $this->where('search', $search)->findOrEmpty();
        if ($exist->isEmpty()) {
            $this::create(['search' => $search]);
        } else {
            $exist->times += 1;
            $exist->save();
        }
    }

    /**
     * 热门搜索
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/18
     *
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function hotSearch(): array
    {
        $search = $this->order('times', 'DESC')->limit(8)->select()->toArray();
        return array_column($search, 'search');
    }
}
